package com.jerry.study.config;

import com.google.common.collect.Lists;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCache;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.GenericToStringSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Created by chedejun on 2017/1/11.
 */
@Configuration
public class CacheConfig extends CachingConfigurerSupport {
    @Bean
    public RedisTemplate redisTemplate(final JedisConnectionFactory connectionFactory) {
        final RedisTemplate redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(connectionFactory);
        redisTemplate.setEnableTransactionSupport(true);
        redisTemplate.setDefaultSerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        redisTemplate.setStringSerializer(new GenericToStringSerializer(Object.class));

        return redisTemplate;
    }

    @Bean(name = "users")
    RedisCache redisCache(final RedisTemplate redisTemplate) {
        return new RedisCache("users", "user:".getBytes(), redisTemplate, 100000L);
    }

    @Bean(name = "orders")
    RedisCache redisCache2(final RedisTemplate redisTemplate) {
        return new RedisCache("orders", "order:".getBytes(), redisTemplate, 100000L);
    }

    @Bean
    public CacheManager cacheManager(final RedisTemplate redisTemplate) {
        final RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);

        redisCacheManager.setCacheNames(Lists.newArrayList("users", "orders"));
        return redisCacheManager;
    }

}
